package ltd.nullpointer.tcp.core.util;

import io.netty.channel.Channel;
import ltd.nullpointer.tcp.core.message.NPiotTCPMessage;
import ltd.nullpointer.tcp.core.SyncFuture;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 
 * @ClassName: ChannelHandlerContextUtil.java
 * @Description: 发送消息的工具类
 * @author zhangweilin
 * @date 2018年1月29日 上午11:23:08
 *
 */
public class ChannelHandlerContextUtil {
	/**
	 * 做TCP同步通信用,
	 */
	public static final Map<String, SyncFuture<NPiotTCPMessage>> syncFutureMap = new ConcurrentHashMap<>();

	public static NPiotTCPMessage sendSync(Channel channel, NPiotTCPMessage npiotTCPMessage) {
		if (npiotTCPMessage == null) {
			throw new IllegalStateException("NPiotTCPMessage can not be null");
		}
		if (null == npiotTCPMessage.getMsgCode()) {
			throw new IllegalStateException(" msgCode of NPiotTCPMessage can not be null");
		}
		npiotTCPMessage.setIsSync(true);
		// npiotTCPMessage.setDeviceId( );
		String messageId = npiotTCPMessage.getMessageId();
		SyncFuture<NPiotTCPMessage> future = syncFutureMap.get(messageId);
		if (null == future) {
			future = new SyncFuture<>();
			syncFutureMap.put(messageId, future);
//			syncFutureMap.put("dddd", future);

		}
		if (channel == null) {
			throw new IllegalStateException();
		}
		channel.writeAndFlush(npiotTCPMessage);
		try {
			NPiotTCPMessage message = future.get();
			return message;
		} catch (InterruptedException e) {
			e.printStackTrace();
			throw new IllegalStateException(" can not get response from the tcp request ", e);
		}
	}

}
